package com.wanghlme.bookstore.incrementer;

import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 实现随机主键 ID 生成器
 *
 * @author WangHailong
 * @see com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator
 */
@Slf4j
@Component
public class CustomIdGenerator implements IdentifierGenerator {

    private final AtomicLong al = new AtomicLong(1);

    @Override
    public Long nextId(Object entity) {
        if (entity == null) {
            return -1L;
        }
        log.info("调用 ID 生成器");
        /* String bizKey = entity.getClass().getName(); */
        String name = entity.getClass().getSimpleName();
        final long id = al.getAndAdd(1);
        log.info("为 {} 对象生成主键值 -> {}", name, id);
        return id;
    }

    @Override
    public String nextUUID(Object entity) {
        if (entity == null) {
            return "";
        }
        log.info("调用 UUID 生成器");
        String name = entity.getClass().getSimpleName();
        String id = IdentifierGenerator.super.nextUUID(entity);
        log.info("为 {} 对象生成主键值 -> {}", name, id);
        return id;
    }
}
